# To change this template, choose Tools | Templates
# and open the template in the editor.

class ZzBookCell < Hash
  def initialize(axis_info_model = nil)
    self['cid'] = "0"
    self['body'] = ""
    if axis_info_model != nil
      set_attr_from_model(axis_info_model)
    end
  end

  def set_attr_from_model(axis_info_model)
    #各セルに書籍の情報を持たせる
    self['cid'] = axis_info_model.id.to_s
    self['body'] = axis_info_model.title
    self['sales_rank'] = axis_info_model.sales_rank
    self['total_reviews'] = axis_info_model.total_reviews
    self['average_rating'] = axis_info_model.average_rating
    self['price'] = axis_info_model.price
    self['number_ofpages'] = axis_info_model.number_ofpages
    self['number_ofclicks'] = axis_info_model.number_ofclicks
    self['publication_date'] = axis_info_model.publication_date.to_s

    if axis_info_model.author_id != nil
      #self['author'] = Author.find(axis_info_model.author_id).author
      self['author'] = $authors[axis_info_model.author_id]
    else
      self['author'] = ''
    end

    if axis_info_model.publisher_id != nil
      #self['publisher'] = Publisher.find(axis_info_model.publisher_id).publisher
      self['publisher'] = $publishers[axis_info_model.publisher_id]
    else
      self['publisher'] = ''
    end

    if axis_info_model.genre != nil
      #self['genre'] = BrowseNode.find(:first,:conditions => ['node_number = ?',axis_info_model.genre]).node_name
      self['genre'] = $genres[axis_info_model.genre]
    else
      self['genre'] = ''
    end

    #画像を取得
    filename = save_file(axis_info_model.medium_image_url)
    self['image'] = filename

    #詳細URLを取得
    if axis_info_model.detail_page_url != nil
      self['detail'] = axis_info_model.detail_page_url
    else
      self['detail'] = ''
    end

  end

  def save_file(url)
    begin
      raise "url is nill" if  url == nil
      raise if url == ""
      basename = "bookimages/" + File.basename(url)
      # %は使用禁止なので_に変える
      basename.gsub!(/%/,'_')
      filename = RAILS_ROOT + "/public/" + basename
      #logger.debug "hogehoge"
      unless File.exists?(filename)
        #ファイルが無い
        open(filename, 'wb') do |file|
          file.puts Net::HTTP.get_response(URI.parse(url)).body
        end
      end
      return basename
    rescue
      #「画像がありません」画像を返す
      return 'bookimages/no-image-no-ciu._SL100_.gif'
    end
  end


end
